<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>弹球游戏(打砖块游戏的一部分)</title>
		<style>
		canvas {    background-color: azure;
					box-shadow: 0 0 40px black;
				    margin: 50px;
				}
		</style>
	</head>
	<body id="b">
		<canvas id="myca" width="400" height="400"
		style="border: solid blueviolet;"></canvas>
		<script>
			function $(id){
				return document.getElementById(id);
			}			
			var ctx=$("myca").getContext("2d");
			var ball={
				x:100, y:150,
				xSpeed:-2,ySpeed:-2 //可以改变其中一个				
			}
			var panel={
				x:200, y:390,
				xSize:50,ySize:5
			}
			var obstacle1={
				x:180, y:150,
				xSize:50,ySize:5
			}
			
			var ob1=true;
		
			var obstacle2={
				x:100, y:150,
				xSize:50,ySize:5
			}
			
			ball.draw=function(){
				ctx.beginPath();
				ctx.fillStyle="darkred";
				ctx.arc(this.x,this.y,10,0,Math.PI*2,false);
				ctx.fill();
			}
			
			
			ball.move=function(){
				this.x=this.x+this.xSpeed;
				this.y=this.y+this.ySpeed;
			}
			
			ball.checkCanvas=function(panelStart,panelEnd){
				
				if(this.x<10||this.x>390)
					this.xSpeed=-this.xSpeed;
				if(this.y<10)this.ySpeed=-this.ySpeed;
				if(this.y>390-5)
				{
					if(this.x>panelStart && this.x<panelEnd)
					   this.ySpeed=-this.ySpeed
					else
					{
						alert("Game Over!!");
						this.x=50;this.y=100;
					}
				}
			}
			ball.checkobstacle=function(panelStart,panelEnd){
				
				if(this.x>panelStart && this.x<panelEnd && this.y-145>0 && 160-this.y>0){
					this.ySpeed=-this.ySpeed;
					ob1=false;
				}
				
				
			}
			
			panel.draw=function(){
				ctx.fillRect(this.x,this.y,this.xSize,this.ySize);
			}
	
				
			obstacle1.draw=function(){
				ctx.fillRect(this.x,this.y,this.xSize,this.ySize);
			}
			obstacle2.draw=function(){
				ctx.fillRect(this.x,this.y,this.xSize,this.ySize);
			}
			
		    setInterval(function(){
					ctx.clearRect(0,0,400,400);
					ball.draw();
					ball.move();
					ball.checkCanvas(panel.x,panel.x+panel.xSize);
					ball.checkobstacle(obstacle1.x,obstacle1.x+obstacle1.xSize);
					panel.draw();
					if(ob1){
						obstacle1.draw();	
					}
					obstacle2.draw();
					ctx.strokeRect(3,3,396,396);
				},30);
			
			$("b").onkeydown=function(e){
				switch(e.keyCode){
				    case 37:
				    panel.x-=5;
					if(panel.x<0)panel.x=0;
				    break;
					case 39:
					panel.x+=5;
					if(panel.x>400-panel.xSize)panel.x=400-panel.xSize;
					break;
				  } 
			}				
		</script>
	</body>
</html>
